//
//  MyScoreViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/8/18.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "MyScoreViewController.h"
#import "TopBackView.h"
#import "ScoreCell.h"
//#import "MineOrderVC.h"
#import "RootViewController.h"
#import "Common.h"
#import <MJRefresh.h>//下拉刷新
#define UmengAppkey @"53290df956240b6b4a0084b3"

#import "RLNetworkHelper.h"//网络判断
#import "WKProgressHUD.h"//提示框
#import "NullView.h"
#define defaultShow 10



@interface MyScoreViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UILabel *scoreLabel;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableDictionary *dataDictionary;


@property (nonatomic) int pageNo;
@property (nonatomic,strong) UIView *netView;
@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NullView *nullView;
@property (nonatomic) NSInteger pageTotal;//最大分页数


@end

@implementation MyScoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [NSMutableArray array];
    self.dataDictionary = [NSMutableDictionary dictionary];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"我的积分"];
    
    [topBackView.rightButton setTitle:@"积分规则" forState:UIControlStateNormal];
    topBackView.rightButton.titleLabel.font = Font(13);
    [topBackView.rightButton setTintColor:WhiteColor];
    [topBackView.rightButton addTarget:self action:@selector(shareMyApp) forControlEvents:UIControlEventTouchUpInside];
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    
    //无网络值的时候
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight) andTitle:@"" andImage:[UIImage imageNamed:@"no_order"]];
    self.nullView.backgroundColor = GrayColor;

    
    self.view.backgroundColor = GrayColor;
    
    [self initDataSources];
    
    [self initSubViews];
    
}

-(void)initDataSources
{
    
    self.nullView.label.text = @"暂无更多积分详情";
    
    
    [Common requestWithUrlString:[NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%d",score_details,self.pageNo,defaultShow] contentType:application_json finished:^(id responseObj) {
        [self.hud dismiss:YES];
        
    
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        self.dataDictionary = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
        
        
        if ([self.dataDictionary[@"turnover"] isEqual:[NSNull null]]) {
            [self.tableView addSubview:self.nullView];

        } else {
            
            self.dataArray = [NSMutableArray arrayWithArray:self.dataDictionary[@"turnover"]];
            [self.nullView removeFromSuperview];
            
            [self.tableView reloadData];
            
        }
        
        if ([self.dataDictionary[@"scores"] isEqual:[NSNull null]]) {
            
        } else {
            self.scoreLabel.text = [NSString stringWithFormat:@"%.2f",[self.dataDictionary[@"scores"] floatValue]];
        }
        
//        if ([responseObj[@"data"][@"turnover"] isEqual:[NSNull null]]) {
//            
//            [self.tableView addSubview:self.nullView];
//            
//        } else {
//           
//            self.dataArray = [NSMutableArray arrayWithArray:self.dataDictionary[@"turnover"]];
//            if (self.dataArray.count > 0) {
//                [self.nullView removeFromSuperview];
//            } else {
//                [self.tableView addSubview:self.nullView];
//            }
//            
//            [self.tableView reloadData];
//
//        }
    
        
    } failed:^(NSString *errorMsg) {
        [self.hud dismiss:YES];
        
        NSLog(@"%@",errorMsg);
    }];

    
}

-(void)initSubViews
{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    [self.view addSubview:self.scrollView];
    
    UIView *firstView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 140 * kHeight)];
    
    firstView.backgroundColor = Color_RGB(252, 161, 87, 1);
    self.scoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 106 * kHeight, 106 * kHeight)];
    self.scoreLabel.center = firstView.center;
    self.scoreLabel.textAlignment = NSTextAlignmentCenter;
    self.scoreLabel.layer.cornerRadius = 53 * kHeight;
    self.scoreLabel.layer.borderColor = WhiteColor.CGColor;
    self.scoreLabel.layer.borderWidth = 1;
    self.scoreLabel.adjustsFontSizeToFitWidth = YES;
    self.scoreLabel.font = Font(34);
    self.scoreLabel.textColor = WhiteColor;
//    self.scoreLabel.text = @"12400";
    [firstView addSubview:self.scoreLabel];
    
    UILabel *scoreL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 200, cellHeight)];
    [firstView addSubview:scoreL];
    scoreL.textColor = WhiteColor;
//    scoreL.text = @"当前积分为:";
    scoreL.font = Font(15);
    
    [self.scrollView addSubview:firstView];
    

//    [self initButtonWithView:firstView];
    [self initTableViewWithView:firstView];
}
/*
-(void)initButtonWithView:(UIView *)view
{
    //积分抽奖按钮
    UIButton *drawButton = [UIButton buttonWithType:UIButtonTypeSystem];
    drawButton.frame = CGRectMake(0, 79 * kHeight, screenWidth/2.0, cellHeight);
    drawButton.backgroundColor = WhiteColor;

    [drawButton setTitle:@"积分抽奖" forState:UIControlStateNormal];
    drawButton.titleLabel.font = Font(13);
    [drawButton setTitleColor:BlackTitleColor forState:UIControlStateNormal];
    [view addSubview:drawButton];
    [drawButton addTarget:self action:@selector(drawButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label = [self backCommonLabelWith:CGRectMake(screenWidth/2.0 - 0.5, 8.5 * kHeight, 1, 26 * kHeight) andColor:GrayColor];
    [drawButton addSubview:label];
    
    //积分说明按钮
    UIButton *showButton = [UIButton buttonWithType:UIButtonTypeSystem];
    showButton.frame = CGRectMake(screenWidth/2.0 , 79 * kHeight, screenWidth/2.0, cellHeight);
    showButton.backgroundColor = WhiteColor;

    [showButton setTitle:@"积分说明" forState:UIControlStateNormal];
    showButton.titleLabel.font = Font(13 );
    [showButton setTitleColor:BlackTitleColor forState:UIControlStateNormal];
    [view addSubview:showButton];
    [showButton addTarget:self action:@selector(showButtonAction) forControlEvents:UIControlEventTouchUpInside];

}
 */

-(void)initTableViewWithView:(UIView *)view
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view.frame) , screenWidth, screenHeight - CGRectGetMaxY(view.frame)) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    //下拉加载
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    //上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
    //无网络状态
    [self createNetWorkAndStatue];

    [self.scrollView addSubview:self.tableView];
      
}


-(void)createNetWorkAndStatue{
    
    //判断是否有网
    [self judgeNetWork];
    //创建加载状态
}

//判断是否有网
-(void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork]) {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
    }
    else{
        [self.netView removeFromSuperview];
        [self initDataSources];
    }
}

//无网络状态
-(void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self initDataSources];
    } else {
        [self.hud dismiss:YES];
    }
}

-(void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}
-(void)downRefresh
{
    if (self.pageNo != 1) {
        self.pageNo --;
        [self judgeNetWork];
        [self.tableView.mj_header endRefreshing];
        
    } else {
        self.tableView.mj_header.state = MJRefreshStateNoMoreData;
        
    }
    [self.tableView.mj_header endRefreshing];
    
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (self.dataArray.count > 0)? self.dataArray.count : 0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = @"scroeCell";
//    
    ScoreCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[ScoreCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.dataArray.count > 0) {
        
        cell.titleLabel.text = self.dataArray[indexPath.row][@"businessTypeText"];
        cell.dateLabel.text = self.dataArray[indexPath.row][@"createTime"];
        
        if ([self.dataArray[indexPath.row][@"score"] integerValue] > 0) {
            
            cell.scoreLabel.text = [NSString stringWithFormat:@"+%@",self.dataArray[indexPath.row][@"score"] ];
            
        } else {
            
            cell.scoreLabel.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"score"] ];
        }
        
        
    }
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     return cellHeight + 10;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    //    return 50 * kHeight;
    return cellHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth/2.0 - 30 * kWidth, cellHeight/2.0 - 10, 60 * kWidth, 20)];
    label.text = @"积分明细";
    label.textColor = carScrollColor;
    label.font = Font(14);
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(35, cellHeight/2.0, CGRectGetMinX(label.frame) - 55, 0.5)];
    
    line1.backgroundColor = LineGrayColor;
    UILabel *line2 = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(label.frame) + 20, cellHeight/2.0, CGRectGetWidth(line1.frame), 0.5)];
    line2.backgroundColor = LineGrayColor;
    [view addSubview:line1];
    [view addSubview:line2];
    view.backgroundColor = WhiteColor;
    
    return view;
}


-(UILabel *)backCommonLabelWith:(CGRect)frame andColor:(UIColor *)color
{
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.backgroundColor = color;
    
    return label;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark 积分抽奖
-(void)drawButtonAction
{
    PrizeViewController *prizeVC = [[PrizeViewController alloc]init];
    [self.navigationController pushViewController:prizeVC animated:YES];
}
#pragma mark 积分说明
-(void)showButtonAction
{
    ShowViewController *showVC = [[ShowViewController alloc]init];
    [self.navigationController pushViewController:showVC animated:YES];

}
 */


#pragma mark 分享
-(void)shareMyApp
{
//    ShowViewController *showVC = [[ShowViewController alloc]init];
//    [self.navigationController pushViewController:showVC animated:YES];
    
    /*
    NSString *shareText = @"使用友盟进行分享";
    UIImage *shareImage = [UIImage imageNamed:@"1"];
    
    NSArray *arr = [NSArray arrayWithObjects:UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline, nil];
    
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:UmengAppkey shareText:shareText shareImage:shareImage shareToSnsNames:arr delegate:self];
    */
    
}

#pragma mark 返回

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
